package com.bing.testNg;

import au.com.bytecode.opencsv.CSVReader;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.testng.annotations.DataProvider;

import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.Iterator;

/**
 * Created by Administrator on 2016/11/21.
 */
public class HelloData implements Iterator {
    private CSVReader reader;
    private String[] last;
    private Class[] parameterTypes;
    private Converter[] parameterConverters;

    public HelloData(Method method) {
        reader = new CSVReader(new InputStreamReader(method.getDeclaringClass().getClassLoader().getResourceAsStream("com/bing/testNg/abc.csv")));
        parameterTypes = method.getParameterTypes();
        parameterConverters = new Converter[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            parameterConverters[i] = ConvertUtils.lookup(parameterTypes[i]);
        }
    }

    @DataProvider(name = "test")
    public static Object[][] createTest() {
        return new Object[][]{
                {1, 2}, {3, 4}
        };
    }

    private String[] getNextLine() {
        if (last == null) {
            try {
                last = reader.readNext();
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);

            }
        }
        return last;
    }

    @Override
    public Object next() {
        String[] next;
        if (last != null) {
            next = last;
        } else {
            next = getNextLine();
        }
        last = null;
        Object[] args = parseLine(next);
        return args;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    private Object[] parseLine(String[] svals) {
        int len = svals.length;
        Object[] ovals = new Object[len];
        for (int i = 0; i < len; i++) {
            ovals[i] = parameterConverters[i].convert(parameterTypes[i], svals[i]);
        }
        return ovals;
    }


    @DataProvider(name = "abc")
    public static Iterator<Object[]> createData(Method method) {
        System.out.println(method.getName());  // print test method name
        Class<? extends Method> aClass = method.getClass();
        Class<?>[] parameterTypes = method.getParameterTypes();

        return new HelloData(method);
    }

    @Override
    public boolean hasNext() {
        return (getNextLine() != null);
    }


}
